package com.hrl.blog.handler;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class ControllerExceptionHandler {

    private final Logger logger =LoggerFactory.getLogger(this.getClass());


    //错误拦截器
    @ExceptionHandler
    public ModelAndView exceptionHandler(HttpServletRequest request, Exception e) throws Exception {
        //处理异常
        logger.error("Request URL : {}, Exception : {}",request.getRequestURL(),e);

        //如果异常带有状态码就不拦截，让spring自己处理
        if(AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class)!=null){
            throw e;
        }


        ModelAndView mv = new ModelAndView();
        //接收异常页面的地址
        mv.addObject("url",request.getRequestURL());
        //异常的信息
        mv.addObject("exception",e);
        //跳转异常处理的页面
        mv.setViewName("error/error");

        return mv;
    }
}
